var Hogan = require('hogan.js');
const { template } = require('lodash');
var config ={
    serverHost : 'http://localhost:80/'
}

var _util = {
    request : function(param){
        var _this = this;
        $.ajax({
            type     : param.method || 'GET',
            url      : param.url || '',
            dataType : param.type || 'json',
            data     : param.data || '',
            xhrFields:{
                withCredentials : true
            },
            success  : function(res){
                if(0 === res.status){
                    if(res.data){
                        typeof param.success === 'function' && param.success(res.data,res.msg);
                    }else{
                        typeof param.success === 'function' && param.success(res.msg);
                    }
                }
                else if(10 === res.status){
                    _this.doLogin();
                }else if(1 === res.status){
                    typeof param.error === 'function' && param.error(res.msg);
                }
            },
            error    : function(errMsg){
                typeof param.error === 'function' && param.error('未连接到服务器');
            }
        });
    },
    doLogin : function(){
        window.location.href = './account-login.html?redirect='+encodeURIComponent(window.location.href);
    },
    getServerURL : function(path){
        return config.serverHost + path;
    },
    validateField : function(fieldType,fieldValue){
        var fieldValue = $.trim(fieldValue);
        if(fieldType === 'require'){
            return !!fieldValue;
        }
        //未来可以增加电话号码、邮箱等的校验
    },
    getURLParam : function(name){
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        var result = window.location.search.substring(1).match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    },
    renderHtml:function(htmlTemplate,data){
        var template = Hogan.compile(htmlTemplate);
        var result = template.render(data);
        return result;
    }
};

module.exports = _util;